<?php
declare(strict_types=1);

namespace App\Controller;

use App\Constants\CacheKey;
use App\Constants\Consts;
use App\Libs\DingDing;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
use Hyperf\View\RenderInterface;
use function Hyperf\Support\env;

/**
 * sitemap管理
 */
class IndataController extends AbstractController
{
    #[Inject(required: true)]
    protected Redis $redis;
    #[Inject(lazy: true)]
    public RenderInterface $view;

    public function index(RequestInterface $request, ResponseInterface $response): Psr7ResponseInterface
    {
        try {
            $post = $request->all();
            $post['group_no'] = trim($request->route('group_no', ''));
            $params = getExtendParams($post);
            $productMaxId = $this->getProductMaxId();

            mt_srand(crc32($params['domain_nowww']));
            $zhongzi = mt_rand(100000, 999999);
            mt_srand(crc32($params['url']));

            // 根据域名固定号的参数：如折扣
            mt_srand(crc32($params['url_nowww']));

            // 根据URL固定的一些参数
            $data['stock'] = mt_rand(100, 3000);
            $data['comment_score'] = round(mt_rand(300, 500) / 100, 2);
            $data['comment_num'] = mt_rand(50, 350);
            $data['campaign_date'] = date('Y.m.d H:i', strtotime('+' . mt_rand(4, 10) . ' day '));
            $data['domain_nowww'] = $params['domain_nowww'];
            $data['hosturl'] = $params['hosturl'];

            // 获取产品信息
            $productId = getProductId($params['url_nowww'], $productMaxId, $zhongzi);
            $product = getProductContent($productId, intval(env('PRODUCTDIR_NUM')));
            // 0-domain,1-product_id,2-product_db,3-cate_name1,4-cate_name2,5-cate_slug1,6-cate_slug2,7-cate_id1,8-cate_id2,9-logo,10-market_price,11-price,12-title,13-intro,14-seo_title,15-$seoDesc
            $data['skuid'] = $productId + $zhongzi;
            $data['cateid1'] = intval($product[7] ?? 0);
            $data['cateid2'] = intval($product[8] ?? 0);
            $data['catename1'] = str_replace('/', '-', $product[3] ?? '');
            $data['catename2'] = str_replace('/', '-', $product[4] ?? '');
            $data['current_url'] = $params['url'];
            $data['logo'] = $product[9] ?? '';
            $data['price'] = number_format(filterZero($product[11] ?? 0));
            $data['jifen'] = ceil(intval($data['price']) / 400);
            // 标题使用正则表达式替换多个空格或全角空格为一个空格
            $data['meta_title'] = $product[12];
            // 番号
            $data['lastid'] = mt_rand(10000000, 99999999);
            // 详情中的图片和文字
            $intro = $product[13] ?? '';
            if (!empty($product[16])) {
                $intro .= $product[16];
            }

            // 将 HTML 内容转换为 UTF-8 编码，并得到最终的图片
            $dom = new \DOMDocument('1.0', 'UTF-8');
            libxml_clear_errors();
            $imghtml = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title></head><body><div>' . htmlspecialchars_decode($intro) . '</div></body></html>';
            if (mb_detect_encoding($imghtml, 'UTF-8', true) === false) {
                $imghtml = mb_convert_encoding($imghtml, 'UTF-8', 'auto');
            }
            @$dom->loadHTML($imghtml, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
            $images = $dom->getElementsByTagName('img');
            $introImgs = $introImages = $proImages = [];
            if (!empty($images)) {
                foreach ($images as $image) {
                    $src = $image->getAttribute('src');
                    $introImgs[] = [
                        'src' => $src,
                        'alt' => $image->getAttribute('alt'),
                    ];
                    $proImages[] = $src;
                }
                shuffle($introImgs);
                $introImgs = array_slice($introImgs, 0, 6);
                foreach ($introImgs as $k => $img) {
                    $j = $k + 1;
                    $introImages[] = [
                        'index' => $j,
                        'alt' => $data['lastid'] . '_' . $j,
                        'img' => $img['src'],
                        'title' => !empty($img['alt']) ? $img['alt'] : $data['meta_title'],
                    ];
                }
                $proImages = json_encode($proImages, JSON_UNESCAPED_UNICODE);
            }

            $introArr = explode("<br/>", $intro);
            $introTexts = '';
            if (!empty($introArr)) {
                $introTexts = [];
                foreach ($introArr as $item) {
                    if (str_contains($item, '<img')) {

                    } else {
                        if (str_contains($item, '商品の説明')) {
                            continue;
                        }
                        if (str_contains($item, '商品の情報')) {
                            continue;
                        }
                        $introTexts[] = $item;
                    }
                }
                $introTexts = array_filter($introTexts);
                $introTexts = !empty($introTexts) ? join("<br/>", $introTexts) : '';
                $introTexts = strip_tags($introTexts, '<br><font><b>');
            }
            $data['intro_texts'] = $introTexts;
            // 跟上谷歌采集的图片
            if (!empty($product[16])) {
                $data['intro_texts'] .= PHP_EOL . $product[16];
            }

            // 获取xxx个A标签链接
            for ($i = 0; $i <= 225; $i++) {
                $lpid = mt_rand(1, $productMaxId);
                $lpid = $lpid + $zhongzi;
                $ahrefs[] = $params['hosturl'] . 'shopdetail/' . $lpid;
            }

            // 12个产品列表
            $prodList = [];
            for ($i = 1; $i <= 15; $i++) {
                $lpid = mt_rand(1, $productMaxId);
                $productContent = $this->redis->get(sprintf(CacheKey::PK, $lpid));
                $lprod = !empty($productContent) ? explode("|||", $productContent) : [];
                if (!empty($lprod) && isset($lprod[2])) {
                    $pMarkerPrice = filterZero($lprod[1]);
                    $lpid = $lpid + $zhongzi;
                    $loc = $params['hosturl'] . 'shopdetail/' . $lpid;
                    $prodList[] = [
                        'lastid' => $lpid + $zhongzi,
                        'href' => $loc,
                        'logo' => $lprod[2] ?? '',
                        'title' => $lprod[0],
                        'price' => number_format($pMarkerPrice),
                        'stock' => mt_rand(200, 2000)
                    ];
                }
            }

            return $this->view->render('JP20-1', compact('ahrefs', 'data', 'introImages', 'proImages', 'prodList'));

        } catch (\Throwable $e) {
            $msg = 'indata error,msg=' . $e->getMessage() . ',file:' . $e->getFile() . ',line:' . $e->getLine();
            logger()->error($msg);
            DingDing::sendErrorMsg($msg);
            return $response->raw('');
        }
    }

    /**
     * 获取最大ID
     */
    private function getProductMaxId()
    {
        $productMaxId = env('PRODUCT_MAXID', 0);
        if (empty($productMaxId)) {
            $productMaxId = $this->redis->get(CacheKey::PRODUCT_MAXID);
            if (!$productMaxId) {
                $productMaxId = @file_get_contents(BASE_PATH . Consts::PRODUCT_COUNT_PATH);
            }
        }
        return intval($productMaxId);
    }
}